package com.uzai.console.service.vph.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.enums.SysMsgTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.CommonUtil;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateFormatUtil;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.vph.vphtoken.*;
import com.uzai.console.entity.Merchant;
import com.uzai.console.entity.PddToken;
import com.uzai.console.entity.VphToken;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.mapper.VphTokenMapper;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.vph.VphTokenService;
import com.uzai.console.vo.vph.vphtoken.VphTokenAuthUrlVo;
import com.uzai.console.vo.vph.vphtoken.VphTokenInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 多多进宝联盟
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class VphTokenServiceImpl implements VphTokenService {

    Logger logger = LoggerFactory.getLogger(VphTokenServiceImpl.class);

    @Value("${vph.token.authorize}")
    private String authorizeUrl;

    @Autowired
    private VphTokenMapper vphTokenMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;

   /**
     * 查询拼多多联盟列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param vphTokenQuery
     * @return null
     */
    public Page<VphTokenInfoVo> findVphTokenList(VphTokenQuery vphTokenQuery){
        Integer now = DateUtil.getNowTime();
        //新建返回到页面的LIST对象
        List<VphTokenInfoVo> vphTokenPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<VphToken> page = new Page<>();
        vphTokenQuery.convert(page);
        ArrayList<VphToken> vphOrderList =  vphTokenMapper.findByList(page, vphTokenQuery);
        if(vphOrderList != null && vphOrderList.size() > 0){
            for (VphToken vphToken : vphOrderList){
                VphTokenInfoVo vphTokenPageVo = new VphTokenInfoVo();
                BeanUtils.copyProperties(vphToken, vphTokenPageVo);

                //到期时间
                Integer expiretime = Tools.getInteger(vphToken.getExpiresTime());
                if(expiretime.intValue() <= now.intValue()){
                    vphTokenPageVo.setExpireStatus(0);  //已到期
                }else if(expiretime.intValue() > now && expiretime.intValue() <= now + 7*24*3600){
                    vphTokenPageVo.setExpireStatus(2);  //即将到期
                }else{
                    vphTokenPageVo.setExpireStatus(1);  //未到期
                }

                vphTokenPageVoList.add(vphTokenPageVo);
            }
        }

        //返回到页面分页对象
        Page<VphTokenInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(vphTokenPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

   /**
     * 添加授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param merId
     * @return null
     */
    public VphTokenAuthUrlVo addVphToken(Long merId){
        //刷新授权的链接，将运营商ID放入自定义参数state当中，授权刷新之后，拼多多调用回调函数返回授权信息
        String url =  authorizeUrl + "v3" + merId;
        VphTokenAuthUrlVo vphTokenAuthUrlVo = new  VphTokenAuthUrlVo();
        vphTokenAuthUrlVo.setUrl(url);
        return vphTokenAuthUrlVo;
    }

   /**
     * 查询联盟详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param vphTokenIdDto
     * @return null
     */
    public VphTokenInfoVo findVphTokenInfo(VphTokenIdDto vphTokenIdDto){

        if(vphTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        VphToken vphToken = vphTokenMapper.selectById(vphTokenIdDto.getId(), vphTokenIdDto.getMerId());
        if(vphToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该拼多多联盟账号不存在");
        }

        //返回页面对象
        VphTokenInfoVo vphTokenInfoVo = new VphTokenInfoVo();
        //将查询到的对象复制给返回页面对象
        BeanUtils.copyProperties(vphToken, vphTokenInfoVo);

        return vphTokenInfoVo;
    }

   /**
     * 保存（兼容添加和修改）
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param vphToken
     * @return null
     */
    public void save(VphToken vphToken) {

        Merchant merchant = merchantMapper.selectById(vphToken.getMerId());
        if (merchant==null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "没有该运营商");
        }

        VphToken at = vphTokenMapper.selectByOpenId(vphToken.getOpenId());
        //该淘宝联盟账号不存在，则新增加
        if (at == null){
            vphTokenMapper.insert(vphToken);

            //发送其他异常提醒
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(merchant.getId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OTHER_EXCEPTION.getValue()); //其他异常提醒
            //消息
            JSONObject ext = new JSONObject();
            StringBuilder content = new StringBuilder();
            content.append("唯品会已增加联盟授权，账号").append(vphToken.getOpenId());
            //当前操作员
            ext.put("content", content.toString());
            ext.put("phone", merchant.getMobile());
            ext.put("errorcode", content.toString());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---唯品会添加联盟授权，发送其他异常消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }else {
            logger.info(at.getMerId() + "::" + vphToken.getMerId());
            if (at.getMerId().longValue() != vphToken.getMerId().longValue()){
                Merchant merchant1 = merchantMapper.selectById(at.getMerId());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, String.format(ResponseMsg.PDD_ACCOUNT_EXIST, CommonUtil.mobileFormat(merchant1.getMobile())));
            }
            vphToken.setId(at.getId());
            int count = vphTokenMapper.updateByIdSelective(vphToken);
            if (count != 1){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,ResponseMsg.NET_ERROR);
            }
        }
    }

   /**
     * 删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param vphTokenIdDto
     * @return null
     */
    public void deleteVphToken(VphTokenIdDto vphTokenIdDto){
        if(vphTokenIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        vphTokenMapper.deleteById(vphTokenIdDto.getId(), vphTokenIdDto.getMerId());
    }

   /**
     * 设置炮灰
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param vphTokenSetPhDto
     * @return null
     */
    public void setPh(VphTokenSetPhDto vphTokenSetPhDto){
        if(vphTokenSetPhDto.getId() == null || vphTokenSetPhDto.getIsPh() == null || vphTokenSetPhDto.getPhOrderCount() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        VphToken vphToken = vphTokenMapper.selectById(vphTokenSetPhDto.getId(), vphTokenSetPhDto.getMerId());

        if(vphToken == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该联盟账号不存在");
        }

        vphToken.setPhOrderCount(vphTokenSetPhDto.getPhOrderCount());
        vphToken.setIsPh(vphTokenSetPhDto.getIsPh());
        //启动炮灰，需要将辅助关闭
//        if(tbTokenSetPhDto.getIsPh().intValue() == 1){
//            tbToken.setIsAux(0);
//        }

        vphTokenMapper.updateById(vphToken);

    }

    /**
     * 授权
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param vphTokenCallBackDto
     * @return null
     */
    public void vphOauth(VphTokenCallBackDto vphTokenCallBackDto){
        String state = vphTokenCallBackDto.getState();
        if(StringUtils.isBlank(state)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "自定义参数不能为空");
        }

        //获取系统版本
        String version = state.substring(0,2);
        //去掉前面2位版本号，为merId_type拼凑的参数
        state = state.substring(2);

        if(StringUtils.isBlank(vphTokenCallBackDto.getTokenInfo())){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "token数据不能为空");
        }
        JSONObject tokenInfo =JSONObject.parseObject(vphTokenCallBackDto.getTokenInfo());
        String openId = tokenInfo.getString("open_id");
        String accessToken = tokenInfo.getString("access_token");
        String create_at = tokenInfo.getString("create_at");
        String expires_time = tokenInfo.getString("expires_time");

        int now = DateUtil.getNowTime();
        VphToken vipToken = new VphToken();
        vipToken.setId(IdWorker.getId());
        vipToken.setOpenId(openId);
        vipToken.setAccessToken(accessToken);
        vipToken.setAuthTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(create_at,"yyyy-MM-dd HH:mm:ss")));
        vipToken.setExpiresTime(DateUtil.getTime(DateFormatUtil.StringToDateFormat(expires_time,"yyyy-MM-dd HH:mm:ss")));
        vipToken.setCreateTime(now);
        vipToken.setUpdateTime(now);

        //3.0系统调用授权
        if("v3".equals(version)){
            vipToken.setMerId(Long.parseLong(state));
            save(vipToken);
        }else{ //2.0系统调用授权，则刷新授权
            VphToken vphToken_old = vphTokenMapper.selectByOpenId(vipToken.getOpenId());
            if(vphToken_old != null){//刷新授权
                vphToken_old.setAccessToken(vipToken.getAccessToken());
                vphToken_old.setExpiresTime(vipToken.getExpiresTime());
                vphToken_old.setAuthTime(now);
                vphToken_old.setUpdateTime(now);
                vphTokenMapper.updateById(vphToken_old);
            }
        }
    }

    @Override
    public List<VphToken> listVphToken(Long merId, List<Long> leagueAccountIds) {
        if (Objects.isNull(merId) || CollectionUtil.isEmpty(leagueAccountIds)) {
            return Lists.newArrayList();
        }
        LambdaQueryWrapper<VphToken> condition = Wrappers.lambdaQuery(VphToken.class);
        condition.eq(VphToken::getMerId, merId).in(VphToken::getId, leagueAccountIds);
        return vphTokenMapper.selectList(condition);
    }

    @Override
    public Boolean updateVphToken(VphTokenDto vphTokenDto) {
        VphToken vphToken = vphTokenMapper.selectById(vphTokenDto.getId(), vphTokenDto.getMerId());
        if (Objects.isNull(vphToken)) {
            throw new BusinessException("唯品会联盟账号不存在");
        }
        VphToken update = new VphToken();
        update.setId(vphToken.getId());
        update.setMerId(vphToken.getMerId());
        update.setRemark(vphTokenDto.getRemark());

        vphTokenMapper.updateByIdSelective(update);
        return true;
    }
}
